from flask import jsonify, request
from flask_login import current_user
from flask.views import MethodView
from app.models.article import Article
from app.extensions import db
from ..auth import auth_required
from app.forms.article import ArticleForm
from webargs import fields
from webargs.flaskparser import parser
from app.decorators import permission_required


parser_args = {
    'page': fields.Int(missing=0, error_messages={'invalid': '必须是数值类型'}),
    'cid': fields.Int(),
}


class ArticleAPI(MethodView):
    decorators = [auth_required]

    def get(self, id):
        if id is not None:
            data = Article.query.get_or_404(id)
            return jsonify(success=True, data=data.to_dict())
        else:
            args = parser.parse(parser_args, request)
            query = Article.query
            data = Article.to_collection_dict(query, args['page'], 20)
            return jsonify(success=True, data=data)

    @permission_required('ADMINISTER')
    def post(self):
        form = ArticleForm(csrf_enabled=False)
        if form.validate_on_submit():
            cid = form.cid.data
            title = form.title.data
            thumb = form.thumb.data
            url = form.url.data
            content = form.content.data
            article = Article(cid=cid,
                              url=url,
                              thumb=thumb,
                              author=current_user.username,
                              title=title,
                              content=content)
            db.session.add(article)
            db.session.commit()
            return jsonify(success=True, data=article.to_dict())

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)
